package com.ruiao.car.service.impl;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruiao.car.config.BusinessException;
import com.ruiao.car.dto.ResultDto;
import com.ruiao.car.entity.Sms;
import com.ruiao.car.enums.ResultEnum;
import com.ruiao.car.mapper.SmsMapper;
import com.ruiao.car.service.ISmsService;
import com.ruiao.car.utils.*;
import lombok.extern.slf4j.Slf4j;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Date;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 短信发送记录 服务实现类
 * </p>
 *
 * @author jsonval@163.com
 * @since 2020-06-12
 */
@Slf4j
@Service
public class SmsServiceImpl extends ServiceImpl<SmsMapper, Sms> implements ISmsService {


	@Value("${account}")
	private String account;

	@Value("${password}")
	private String pswd;

	@Value("${url}")
	private String url;

	@Value("${isSend}")
	private Boolean isSend;

	private  String denglu = "【评车帝】您正在登录账号，验证码为：${ver}，5分钟内有效，请尽快完成验证，谢谢！";
	private  String zhuce = "【评车帝】您正在进行注册，验证码为：${ver}，5分钟内有效，请尽快完成验证，谢谢！";


	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Sms selectSmsByPhone(String smsType, String phone,String appId,int status) {
		QueryWrapper queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("mobile", phone);
		queryWrapper.eq("app_id", appId);
		queryWrapper.eq("status", status);
		queryWrapper.eq("type", Byte.valueOf(smsType));
		queryWrapper.orderByDesc("create_date");
		queryWrapper.last(" limit 1");
		return this.getOne(queryWrapper);
	}
	
	@Override
	public Sms selectSmsByPhone(Sms param) {
		HeaderUtil headerUtil = AccountThreadLocal.get().getHeaderUtil();
		return this.selectSmsByPhone(param.getType().toString(),param.getMobile(),headerUtil.getAppId(),1);
	}

	@Override
	public void updateSms(Sms param) {
		this.baseMapper.updateById(param);
	}

	@Override
	public ResultDto sendSms(String smsType, String phone) throws BusinessException {
		if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(smsType)) {
			throw new BusinessException(ResultEnum.LOSE_PARAM);
		}
		HeaderUtil headerUtil = AccountThreadLocal.get().getHeaderUtil();
		String appId = headerUtil.getAppId();
		Sms sms = selectSmsByPhone(smsType,phone,appId,1);
		// 判断5分钟之内发送过
		if (null != sms 
		 && (new Date().before(DateUtils.getBeforeDate(sms.getCreateDate(), 5)))) {
			sms.setStatus((byte)0);
			this.baseMapper.updateById(sms);
			throw new BusinessException(ResultEnum.CODE_SMS_OFTEN);
		}

		sms = new Sms();
		String code = SnowflakeIdWorker.randomNum();
		log.info("===验证码是；{}==",code);
		sms.setStatus((byte)1);
		sms.setType(Byte.valueOf(smsType));
		sms.setCode(code);
		sms.setMobile(phone);
		sms.setAppId(appId);
		sms.setCreateDate(new Date());
		//sms.setChannel(channel);
		String res = this.sendSms(sms);
		if (res.equalsIgnoreCase("OK")) {
			return new ResultDto(ResultEnum.SUCCESS, code);
		} else {
			throw new BusinessException(ResultEnum.CODE_SMS_FAILED);
		}
	}

	public String sendSms(Sms sms) {
		this.baseMapper.insert(sms);

		if(isSend == false){
			log.warn("系统配置不发短信,直接返回true");
			return "OK";
		}
		try {
			String message = "";
			String sendResult = null;
			log.info("start send message to ：" + sms.getMobile());
			if(sms.getType() == 1) {
				message = "【评车帝】您正在进行注册，验证码为："+ sms.getCode() +"，5分钟内有效，请尽快完成验证，谢谢！";
			} else if (sms.getType() == 2) {
				message = "【评车帝】您正在登录账号，验证码为："+ sms.getCode() + "，5分钟内有效，请尽快完成验证，谢谢！";
			}
			sendResult = doPostRequest(sms.getMobile(), message);
			if (sendResult == null) {
				log.info("消息返回数据是null");
				return "nook";
			}

			JSONObject jsonObject = JSONUtil.parseObj(sendResult);

			if ("0".equals(jsonObject.getStr("code"))) {
				return "OK";
			}

		} catch (Exception e) {
			log.warn("发送消息失败", e);
		}
		return "OK";
	}


	/**
	 * 发送创蓝短信
	 *
	 * @param mobile  手机号
	 * @param content 内容
	 * @return
	 */
	public String doPostRequest(String mobile, String content) {
		String returnString = null;
		try {
			returnString = HttpSender.batchSend(url, account, pswd, mobile, content);
		} catch (Exception e) {
			log.error("创蓝短信发送时发生异常", e);
		}
		return returnString;
	}

}
